package jjn.carl.hashtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-07-04 23:10
 */
public class LeetCode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        long res = 0L;
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length - 3; i++) {
            if (nums[i] > 0 && nums[i] > target && target >= 0) {
                return result;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1, right = nums.length - 1;
                while (left < right) {
                    long cur = (long) nums[i] + (long) nums[j] + (long) nums[left] + (long) nums[right];
                    if (cur < target) {
                        left++;
                    } else if (cur > target) {
                        right--;
                    } else {
                        result.add(List.of(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        int[] nums = new int[]{1, 0, -1, 0, -2, 2};
        int target = 0;
        List<List<Integer>> fourSum = new LeetCode18().fourSum(nums, target);
        System.out.println("fourSum = " + fourSum);
        nums = new int[]{2, 2, 2, 2, 2, 2};
        target = 8;
        fourSum = new LeetCode18().fourSum(nums, target);
        System.out.println("fourSum = " + fourSum);
        nums = new int[]{1000000000, 1000000000, 1000000000, 1000000000};
        target = -294967296;
        fourSum = new LeetCode18().fourSum(nums, target);
        System.out.println("fourSum = " + fourSum);
    }
}
